<?php
require_once('../includes/mysql.connect.php');

/*
 * This is the "official" OO way to do it,
 * BUT $connect_error was broken until PHP 5.2.9 and 5.3.0.
 */
if ($mysqli->connect_error) {
    die('Connect Error (' . $mysqli->connect_errno . ') '
            . $mysqli->connect_error);
}

/*
 * Use this instead of $connect_error if you need to ensure
 * compatibility with PHP versions prior to 5.2.9 and 5.3.0.
 */
if (mysqli_connect_error()) {
    die('Connect Error (' . mysqli_connect_errno() . ') '
            . mysqli_connect_error());
}


$query = "SELECT * FROM `layers`"; // Build the start of the query
if (!isset($_GET['layers']) || $_GET['layers'] == '') {  // if layers is not set or empty, go with the default layers
	$query .= ' WHERE `includeinLayersConfig` > 0';
	$defaultLoad = true;
}
else {//if it is set, check whether it's all or a list of layers
	if ($_GET['layers'] == 'all') {
		//Do nothing because the query is already setup correctly.
	}
	else {// if it's not "all" it must be a list of layers (or individual layer).   
		$query .= ' WHERE `id` LIKE "'.mysqli_real_escape_string($mysqli, $_GET['layers']).'"';
	}	
}



if ($result = $mysqli->query($query)) {
    for ($i=0; $i < ($result->num_rows); $i++) {
        $row = $result->fetch_array(MYSQLI_ASSOC);
        if ($row['infowindow'] != null) {
            //print('infowindow: '.$row['infowindow']."\n");
            $row['infowindow'] = json_decode($row['infowindow']);
            //print_r($row['infowindow']);
            //print("\n");
        }
        if ($defaultLoad) {
        	unset($row['includeinLayersConfig']);
        }
        $layersJSON[$i] = $row;        
        
    }
}
$layersJSON = json_encode($layersJSON);
print($layersJSON);             
 /* free result set */
$result->close();
?>